﻿using com.citizensoft.MessageExchange.Ext;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;

namespace com.citizensoft.MessageExchange
{
    public class Message
    {
        public long Sequence { get; set; }
        public string MessageType { get; set; }
        public Dictionary<string, object> Parameters { get; set; }
        public bool Compressed {get;set;}

        public byte[] ToByte()
        {
            string jsonstring = JsonConvert.SerializeObject(this);
            byte[] extensions = new byte[4];
            List<byte> result = new List<byte>(BitConverter.GetBytes(Sequence));
            if (Compressed)
            {
                extensions[0] = 1;
                result.AddRange(GZip.Compress(Encoding.UTF8.GetBytes(jsonstring)));
            }
            else
            {
                extensions[0] = 0;
                result.AddRange(Encoding.UTF8.GetBytes(jsonstring));
            }
            result.InsertRange(8, extensions);
            byte[] crc = BitConverter.GetBytes(Crc32.Compute(result.ToArray()));
            byte[] len = BitConverter.GetBytes(result.Count + crc.Length);
            result.InsertRange(0, crc);
            result.InsertRange(0, len);
            return result.ToArray();
        }

        public void WriteTo(Stream stream)
        {
            try
            {
                byte[] data = this.ToByte();
                stream.Write(data, 0, data.Length);
                stream.Flush();
            }
            catch { }
        }

        public static Message FromByte(byte[] bytes)
        {
            if (bytes.Length >= 20)
            {
                byte[] crc = bytes.Skip(4).Take(4).ToArray();
                byte[] computecrc = BitConverter.GetBytes(Crc32.Compute(bytes.Skip(8).ToArray()));
                byte[] extensions = bytes.Skip(16).Take(4).ToArray();
                if (crc[0] == computecrc[0] && crc[1] == computecrc[1] && crc[2] == computecrc[2] && crc[3] == computecrc[3])
                {
                    Message message = null;
                    if (extensions[0] == 0)
                    {
                        message = JsonConvert.DeserializeObject<Message>(Encoding.UTF8.GetString(bytes.Skip(20).ToArray()));
                    }
                    else
                    {
                        message = JsonConvert.DeserializeObject<Message>(Encoding.UTF8.GetString(GZip.Decompress(bytes.Skip(20).ToArray())));
                    }
                    message.Sequence = BitConverter.ToInt64(bytes.Skip(8).Take(8).ToArray(), 0);
                    return message;
                }
            }
            return null;
        }
    }
}
